package com.ruoyi.common.utils.file;

import java.io.IOException;
import java.io.InputStream;

import io.minio.*;
import lombok.SneakyThrows;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import io.minio.http.Method;

/**
 * Minio 文件存储工具类
 */
public class MinioUtil
{

    /**
     * 检查存储桶是否存在
     *
     * @param bucketName 存储桶名称
     * @return
     */
    @SneakyThrows
    public static boolean bucketExists(String bucketName)
    {
        return SpringUtils.getBean(MinioClient.class).bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    /**
     * 创建存储桶
     *
     * @param bucketName 存储桶名称
     */
    @SneakyThrows
    public static void makeBucket(String bucketName)
    {
        if (!bucketExists(bucketName))
        {
            SpringUtils.getBean(MinioClient.class).makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    /**
     * 上传文件
     *
     * @param bucketName 桶名称
     * @param fileName
     * @throws IOException
     */
    public static String uploadFile(String bucketName, String fileName, MultipartFile multipartFile) throws IOException
    {
        makeBucket(bucketName);
        String url = "";
        MinioClient minioClient = SpringUtils.getBean(MinioClient.class);
        try (InputStream inputStream = multipartFile.getInputStream())
        {

            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(inputStream,
                    multipartFile.getSize(), -1).contentType(multipartFile.getContentType()).build());

            url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().bucket(bucketName).object(fileName).method(Method.GET).build());
            url = url.substring(0, url.indexOf('?'));
            return ServletUtils.urlDecode(url);
        } catch (Exception e)
        {
            throw new IOException(e.getMessage(), e);
        }
    }

    //下载文件: downloadFile方法允许用户下载指定存储桶中的文件，并返回该文件的输入流。
    public static InputStream downloadFile(String bucketName, String filename) throws Exception
    {
        return SpringUtils.getBean(MinioClient.class).getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(filename)
                .build());
    }
}
